﻿using UnityEngine;
using System.Collections.Generic;
using System.IO;
using UnityEditor;


public class PackageAssetBundle : EditorWindow
{
    public const string PATH = "Assets/packageFile.txt";         //需要打包文件配置表
    private string TargetPrefix = Application.streamingAssetsPath + "/";
    enum PLATFORMS
    {
        pc,
        wp8,
        android,
        ios,
    }
    private PLATFORMS mPlatform = 0;
    private List<string> mFileList = new List<string>();
    // Use this for initialization
    [MenuItem( "AssetBundleDemo/platform Package" )]
    static void PackageBundle()
    {
        PackageAssetBundle window = (PackageAssetBundle)EditorWindow.GetWindow( typeof( PackageAssetBundle ), true, "Packing tools" );
        window.Show();
    }
    void Awake()
    {
        initFileList();
    }
    void OnGUI()
    {
        mPlatform = (PLATFORMS)EditorGUILayout.EnumPopup( "platform", mPlatform );
        if( GUILayout.Button( "Package" ))
        {
            Package();
        }
    }
    void Package()
    {
        List<Object> packageFiles = new List<Object>();
        foreach( string file in mFileList )
        {
            Object obj = AssetDatabase.LoadMainAssetAtPath( file );
            packageFiles.Add( obj );
        }
        switch( mPlatform )
        {
            case PLATFORMS.pc:
                BuildPlatform(BuildTarget.StandaloneWindows, packageFiles);
                break;
            //case PLATFORMS.wp8:
            //    BuildPlatform(BuildTarget.WebPlayer, packageFiles);
                break;
            case PLATFORMS.android:
                BuildPlatform(BuildTarget.Android, packageFiles);
                break;
            case PLATFORMS.ios:
                BuildPlatform(BuildTarget.iOS, packageFiles);
                break;
            default:
                Debug.Log("platformError!");
                break;
        }
    }
    private void BuildPlatform( BuildTarget target, List<Object> packageFile )
    {
        string wholePath = TargetPrefix + mPlatform.ToString() + "/";
        if( !Directory.Exists( wholePath ) )
        {
            Directory.CreateDirectory( wholePath );
        }
        for( int i = packageFile.Count - 1; i >= 0; i-- )
        {
            Object obj = packageFile[i];
            string sourcePath = AssetDatabase.GetAssetPath( obj );
            AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
            buildMap[0].assetBundleName = obj.name + ".assetbundle";
            string[] resourcesAssets = new string[1];
            resourcesAssets[0] = sourcePath;
            buildMap[0].assetNames = resourcesAssets;
            BuildPipeline.BuildAssetBundles( wholePath, buildMap, BuildAssetBundleOptions.ForceRebuildAssetBundle | BuildAssetBundleOptions.DeterministicAssetBundle, target );
            
        }
        Selection.objects = packageFile.ToArray();
        AssetDatabase.Refresh();
    }
    [MenuItem( "AssetBundleDemo/Package AssetBundle" )]
    static void CreateAssetBundle(BuildTarget target,List<Object> packageFile)
    {
        Debug.Log( "start" );
        Object[] selects = Selection.GetFiltered( typeof( Object ), SelectionMode.DeepAssets );
        foreach( Object obj in selects )
        {
            //这里建立一个本地测试  
            //注意本地测试中可以是任意的文件，但是到了移动平台只能读取路径StreamingAssets里面的  
            //StreamingAssets是只读路径，不能写入  
            string targetPath = Application.dataPath + "/StreamingAssets/pc/" + obj.name + ".assetbundle";//文件的后缀名是assetbundle和unity都可以  
            //if( BuildPipeline.BuildAssetBundle( obj, null, targetPath, BuildAssetBundleOptions.CollectDependencies ) )
            //{

            //    Debug.Log( obj.name + "is packed successfully!" );
            //}
            //else
            //{
            //    Debug.Log( obj.name + "is packed failly!" );
            //}
        }
        AssetDatabase.Refresh();
    }
    private void initFileList()
    {
        mFileList.Clear();
        string[] files = File.ReadAllLines( PATH );
        for( int i = 0; i < files.Length; ++i )
        {
            string subFilePath = files[i].Trim().Replace( '\\', '/' );
            if( subFilePath == "" )
            {
                continue;
            }
            string wholePath = "Assets/" + subFilePath;
            if( !isFilePathValid( wholePath ) )
            {
                Debug.LogError( string.Format( "{0} line {1}: error - {2} may be something wrong", PATH, ( i + 1 ), wholePath ) );
                continue;
            }
            mFileList.Add( wholePath );
        }
    }
    private bool isFilePathValid( string file )
    {
        if( !File.Exists( file ) )
        {
            return false;
        }
        Object obj = AssetDatabase.LoadMainAssetAtPath( file );
        if( obj == null )
        {
            return false;
        }
        if( mFileList.Contains( file ) )
        {
            return false;
        }
        return true;
    }
}


